package cn.fboost.mtos.util;

import cn.fboost.mtos.dto.internal.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Session工具类
 * 负责从Redis中存取Session
 */
@Component
public class SessionUtil {
    private static final String SESSION_PREFIX = "MTOS:session:";
    private static final int SESSION_EXPIRE = 7200;
    private final RedisTemplate<String, Session> redisTemplate;

    public SessionUtil(RedisTemplate<String, Session> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取Session
     * @param token Token
     * @return {@link Session}
     */
    public Session getSession(String token) {
        return redisTemplate.opsForValue().get(SESSION_PREFIX + token);
    }

    /**
     * 设置Session
     *
     * @param token Token
     * @param session {@link Session}
     */
    public void setSession(String token, Session session) {
        redisTemplate.opsForValue().set(SESSION_PREFIX + token, session, SESSION_EXPIRE, TimeUnit.SECONDS);
    }

    /**
     * 删除Session
     *
     * @param token Token
     */
    public void deleteSession(String token) {
        redisTemplate.delete(SESSION_PREFIX + token);
    }

    /**
     * 刷新Session过期时间
     *
     * @param token Token
     * @param session {@link Session}
     */
    public void refreshSession(String token, Session session) {
        if (Boolean.FALSE.equals(redisTemplate.expire(SESSION_PREFIX + token, SESSION_EXPIRE, TimeUnit.SECONDS))) {
            // 如果刷新失败，重新设置
            setSession(token, session);
        }
    }
}
